package com.github.caijinglong.handler

import com.github.caijinglong.SaveDataHandler
import com.github.caijinglong.relicsJson
import org.json.JSONArray
import org.json.JSONObject

class RelicsHandler : SaveDataHandler {

    override var jsonObject: JSONObject = JSONObject()

    fun handleJSON(runnable: (jsonArray: JSONArray) -> Unit) {
        val k = "relics"
        val array = jsonObject.getJSONArray(k)
        runnable(array)
        jsonObject.put(k, array)
    }

    fun addRelics(relicsName: String) {
        handleJSON { a ->
            if (a.toList().contains(relicsName).not()) {
                a.put(relicsName)
            }
        }
    }

    fun addRelics(vararg relicsNames: String) {
        addRelics(relicsNames.asList())
    }

    fun addRelics(iterator: Iterable<String>) {
        handleJSON { a ->
            iterator.forEach {
                if (a.toList().contains(it).not()) {
                    a.put(it)
                }
            }
        }
    }

    fun trans(number: Int) {
        val k = "relics"
        val array = jsonObject.getJSONArray(k)
        val strList = arrayListOf<String>()
        array.toMutableList().filterIndexed { index, any ->
            index < number
        }.forEach {
            if (it is String) {
                strList.add(it)
            }
        }
        val a = JSONArray(strList)
        jsonObject.put(k, a)
    }

    fun putBuffRelics() {
        val li = ArrayList<String>()
        JSONArray(relicsJson).toList().filter { it is String }.forEach {
            if (it is String) {
                li.add(it)
            }
        }

        addRelics(li)
    }
}